/**
 * Created by Administrator on 2015-3-4.
 */
var models = require('./models') ;    // 导入自定义组件
var Pa = models.pa;
var Cp = models.cp;
var EventProxy = require('eventproxy');
var Paginate = require('./Paginate');
var async = require('async');


var listPaAndPaginate = function (condition,page,perPage,opt,callback){
    if(!condition){
        condition = {};
    }
    if(!opt){
        opt = {};
    }
    //计算分页信息
    if(!perPage || perPage < 1){
        perPage = 20;
    }
    var skip = 0;
    if(page && page > 1){
        skip = (page-1) * perPage;
    }
    opt['skip'] = skip;
    opt['limit'] = perPage;
    var ep = new EventProxy();
    ep.fail(callback);
    ep.all('total','pa',function(total,pa){
        var paginate = new Paginate(page,perPage,total,pa);
        callback(null,paginate);
    });
    //计算总数
    Pa.count(condition,ep.done('total'));
    //查询当前页产品信息
    Pa.find(condition,{},opt,ep.done('pa'));
};

/**
 * 浏览所有组件信息
 * @param req
 * @param res
 */
exports.getPaAll = function(req,res){
    var pageNum = req.body.pageNum;
    var numPerPage = req.body.numPerPage;
    if(pageNum =='undefined' || numPerPage =='undefined'){
        pageNum = 1;
        numPerPage = 20;
    }
    var condition = {};
    var sn = req.body.pasn;
    var pn = req.body.paname;
    var bn = req.body.pabn;
    if(sn||pn||bn){
        condition = {pasn : new RegExp(sn),pana : new RegExp(pn),pabn : new RegExp(bn)};
    }
    listPaAndPaginate(condition,pageNum,numPerPage,{sort:{_id:-1},pavb:true},function(err,paginate){
        if(err){
            next(err);
        }else{
            if(!paginate){
                res.send('没有数据！');
            }else{
                var page = paginate.page;
                var perPage = paginate.perPage;
                var total = paginate.total;
                var items = paginate.items;
                res.render('pa_list',{pas : items,page : page,perPage : perPage,total : total,sn:sn,pn:pn,bn:bn});
            }
        }
    });
};

/**
 * 批量添加组件信息
 * @param req
 * @param res
 */
exports.batchAddPaUi = function(req,res){
    res.render('batch_add_pa');
};
exports.batchAddPa = function(req,res){
    var sn1 = req.body.paSn1;
    var sn2 = req.body.paSn2;
    var paArray = new Array();
    for(var i = sn1; i <= sn2; i++){
        var newPa = new Pa({
            pasn : i,
            pana : req.body.paName,
            patp : req.body.paType,
            pavn : req.body.paVa,
            pada : req.body.paData,
            pami : req.body.paMi,
            pabn : req.body.paBn,
            papa : req.body.paPa,
            pads : req.body.paDs,
            past : req.body.paState,
            pavb : 1
        });
        paArray.push(newPa);
    }
    Pa.create(paArray,function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败  请检查是否有SN已存在！"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"paList","forwardUrl":"", "callbackType":"closeCurrent"}');
        };
    });
};

/**
 * 编辑组件信息
 * @param req
 * @param res
 */
exports.updatePaOneUi = function(req,res){
    var paId = req.param('paid');
    Pa.findById(paId,function(err,pa){
        res.render('update_pa',{pa:pa});
    });
};
exports.updatePaOne = function(req,res){
    var paId = req.body.paId;
    Pa.findById(paId,function(err,doc){
        doc.pasn = req.body.paSn;
        doc.pana = req.body.paName;
        doc.patp = req.body.paType;
        doc.pavn = req.body.paVa;
        doc.pada = req.body.paData;
        doc.pami = req.body.paMi;
        doc.pabn = req.body.paBn;
        doc.papa = req.body.paPa;
        doc.pads = req.body.paDs;
        doc.past = req.body.paState;
        doc.save(function(err){
            if(err){
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"paList","callbackType":"closeCurrent","forwardUrl":""}');
            }
        });
    });
};

/**
 * 批量删除组件信息
 * @param req
 * @param res
 */
exports.batchDelPa = function(req,res){
    var paids = req.param('ids');
    Pa.remove({_id : {$in : paids.split(',')}},function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"paList","forwardUrl":""}');
        };
    });
};

/**
 * 将组件和产品关联
 * @param req
 * @param res
 */
exports.paInCp = function(req,res){
    var paSnStr = req.body.pasns;
    var pss = paSnStr.substring(1,paSnStr.length-1);
    var psArr = pss.split(',');
    async.waterfall([
        function(callback){
            var noPasnArr = new Array();
            psArr.forEach(function(ps){
                Pa.findOne({pasn:ps.trim()},{'_id':1},function(err,doc){
                    if(doc){
                    }else{
                        noPasnArr.push(ps);
                    }
                });
            });
            setTimeout(function(){
                callback(null,noPasnArr);
            },500);
        },
        function(noPasnArr,callback){
            var paIdArr = new Array();
            if(noPasnArr.length==0){
                psArr.forEach(function(ps){
                    Pa.findOne({'pasn':ps.trim()},{'past':1},function(er,pa){
                        if(pa){
                            pa.past = 1;
                            paIdArr.push(pa._id);
                            pa.save();
                        }else{
                            res.send('0');
                        }
                    });
                });
                setTimeout(function(){callback(null,paIdArr,noPasnArr);},500);
            }else{
                callback(null,paIdArr,noPasnArr);
            }
        },
        function(paIdArr,noPasnArr,callback){
            if(paIdArr.length != 0){
                var cpSn = req.body.cpsn;
                Cp.findOne({sn:cpSn},{'ass':1},function(err,cp){
                    if(cp){
                        cp.ass.remove();
                        cp.ass = paIdArr;
                        cp.save(function(e){
                            if(e){
                                callback(null,'0');
                            } else{
                                callback(null,'1');
                            }
                        });
                    }else{
                        callback(null,cpSn+'二维码不存在！');
                    };
                });
            }else{
                callback(null,noPasnArr+'条码不存在！');
            };
        }
    ],function(err,result){
        res.send(result);
    });
};


/**
 * 批量添加部署地信息
 * 如果有一个二维码不存在则所有都不做修改，返回错误的二维码和输入的部署地信息
 * @param req
 * @param res
 */
exports.batchAddDs1 = function(req,res){
    var snds = req.body.snDs;
    var sndsArr = snds.split(',');
    console.log(sndsArr);
    async.waterfall([
        function(callback){
            var noCpsnArr =  new Array();
            sndsArr.forEach(function(snds){
                var sdArr = snds.split('_');
                Cp.findOne({sn:sdArr[0].trim()},{'_id':1},function(err,doc){
                    if(doc!=null){
                    }else{
                        console.log('错误'+doc);
                        noCpsnArr.push(snds);
                    };
                });
            });
            setTimeout(function(){callback(null,noCpsnArr)},1000);
        },
        function(noCpsnArr,callback){
            if(noCpsnArr.length != 0){
                console.log(noCpsnArr.toString()+'数据不存在！');
                callback(null,'添加失败，'+noCpsnArr.toString()+'数据不存在！');
            }else{
                console.log("无错误数据！");
                sndsArr.forEach(function(snds){
                    var sdArr = snds.split('_');
                    Cp.findOne({sn:sdArr[0].trim()},{'ds':1,'ass':1}, function (err,doc) {
                        doc.ds = sdArr[1];
                        var assIdArr = doc.ass;
                        assIdArr.forEach(function(paId){
                            Pa.findById(paId,{'paus':1},function(err,doc){
                                doc.paus = sdArr[1];
                                doc.save();
                            });
                        });
                        doc.save();
                    });
                });
                setTimeout(function(){callback(null,'1')},1000);
            }
        }

    ],function(err,result){
        res.send(result);
    });
};


/**
 * 批量添加部署地信息
 * 如果有错误的二维码数据，则其他正确的都完成修改，将错误的二维码+部署地信息返回
 * @param req
 * @param res
 */
exports.batchAddDs = function(req,res){
    async.waterfall([
        function(callback1){
            var snds = req.body.snDs;
            var sndsArr = snds.split(',');
            var noCpsnArr =  new Array();
            for(var i = 0;i<sndsArr.length;i++){
                fixOne(sndsArr[i],noCpsnArr);
            }
            setTimeout(function(){callback1(null,noCpsnArr)},30000);
        },
        function(noCpsnArr,callback){
            console.log(noCpsnArr);
            if(noCpsnArr.length != 0){
                callback(null,'添加失败，'+noCpsnArr.toString()+'数据不存在！');
            }else{
                callback(null,'1');
            }
        }
    ],function(err,result){
       console.log('result='+result);
       res.send(result);
    });
};


/**
 * 修改一个部署地
 * @param callback
 */
function fixOne(sndsStr,noCpsnArr){
    var arr = sndsStr.split('_');
    //console.log(arr[0]);
    Cp.findOne({sn:arr[0].trim()},{'ds':1,'ass':1}, function (err,product) {
        if(product!=null){
            product.ds = arr[1];
            product.save();
            (product.ass).forEach(function(paId){
                console.log(arr[0]+product.ds);
                Pa.findById(paId,{'paus':1},function(err,comp){
                    if(err){
                        console.log('查询组件时异常：'+err);
                    }else{
                        comp.paus = product.ds;
                        comp.save();
                        console.log('组件用户:'+product.ds+'update OK!');
                    }
                });
            });
        }else{
            noCpsnArr.push(sndsStr);
            console.log('错误的'+arr[0]);
        }
    });
}

exports.test = function(){
    var list = ['21000390_aaa-01','21000391_aaa-02','21000392_aaa-03','21000393_aaa-04'];
    for(var i=0;i<list.length;i++){
        console.log('>>> cp:', list[i]);
        fixOne(list[i]);
    }
};

/**
 * 通过调用该程序批量修改错误的部署地信息
 * 因为哈尔滨项目部署地信息缺失“哈尔滨”
 */
exports.batchUpdateDs = function(req,res){
    Pa.find({paus:new RegExp('B03-1-1')},{'pasn':1,'paus':1},function(err,cps){
        console.log('一共查询出：'+cps.length+'条记录！');
        cps.forEach(function(cp){
            cp.paus='哈尔滨'+cp.paus;
            cp.save();
        });
    });
    res.send(null);
};

exports.getCpByPra = function(req,res){
    Pa.find({paus:new RegExp('B03-1-1')},{'pasn':1,'paus':1},function(err,cps){
        console.log(cps);
        console.log('查询结果条数='+cps.length);
    });
    res.send(null);
};


/**
 * 添加一条部署地信息
 */
exports.addDsOne = function(req,res)
{
    //var cpsn = req.body.cpsn;
    var cpsn = req.param('cpsn');
    console.log(cpsn);
    //var dsStr = req.body.ds;
    var dsStr = req.param('ds');
    console.log(dsStr);
    if(cpsn==null || cpsn==''){
        res.send("二维码"+cpsn+"不存在！");
    }else if(dsStr==null || dsStr==''){
        res.send("二维码"+cpsn+"的部署地信息为空！");
    }
    Cp.findOne({sn:cpsn.trim()},{'ds':1,'ass':1},function(err,doc){
        if(err || doc==null){
            res.send("二维码"+cpsn+"不存在！");
        }else{
            doc.ds = dsStr;
            var assIdArr = doc.ass;
            assIdArr.forEach(function(paId){
                Pa.findById(paId,{'paus':1},function(err,doc){
                    doc.paus = dsStr;
                    doc.save();
                });
            });
            doc.save();
            res.send('1');
        }
    });
};

/**
 * 时间转换
 * @param now
 * @returns {string}
 */
function formatDate(now)   {
    var year = now.getFullYear();
    var month =now.getMonth() + 1;
    var day = now.getDate();
    var   hour = now.getHours();
    var   minute = now.getMinutes();
    var   second = now.getSeconds();
    return   year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
};

/**
 * 标记返修
 * @param req
 * @param res
 */
exports.addPaRepairRecords = function (req,res){
    var pasnStr = req.body.pasns;
    var flg = req.body.flg;
    var pasnS = pasnStr.substring(1,pasnStr.length-1);
    var pasnArr = pasnS.split(',');
    if(flg=='1'){
        async.waterfall([
            function(callback){
                var noPasnArr = new Array();
                pasnArr.forEach(function(sn){
                    Pa.findOne({pasn:sn.trim()},{'_id':1},function(err,doc){
                        if(doc){}else{
                            noPasnArr.push(sn);
                        }
                    });
                });
                setTimeout(function(){callback(null,noPasnArr);},500);
            },
            function(noPasnArr,callback){
                if(noPasnArr != 0){
                    callback(null,'操作失败，条码'+noPasnArr+'不存在！');
                }else{
                    pasnArr.forEach(function (pasn) {
                        Pa.findOne({pasn:pasn.trim()},{'pamrs':1,'palog':1,'past':1}, function (err,pa) {
                            pa.pamrs.push({pmt:formatDate(new Date()),pmc:'返厂维修'});
                            pa.past = 2;
                            pa.save();
                        });
                    });
                    callback(null,'1');
                }
            }
        ],function(err,result){
            res.send(result);
        });
    }else{
        async.waterfall([
            function(callback){
                var noPasnArr = new Array();
                pasnArr.forEach(function(sn){
                    Pa.findOne({pasn:sn.trim()},{'_id':1},function(err,doc){
                        if(doc){}else{
                            noPasnArr.push(sn);
                        }
                    });
                });
                setTimeout(function(){callback(null,noPasnArr);},500);
            },
            function(noPasnArr,callback){
                if(noPasnArr != 0){
                    callback(null,'操作失败，条码'+noPasnArr+'不存在！');
                }else{
                    pasnArr.forEach(function (pasn) {
                        Pa.findOne({pasn:pasn.trim()},{'pamrs':1,'palog':1,'past':1}, function (err,pa) {
                            pa.pamrs.push({pmt:formatDate(new Date()),pmc:'维修完成并扫描登记'});
                            pa.past = 0;
                            pa.save();
                        });
                    });
                    callback(null,'1');
                }
            }
        ],function(err,result){
            res.send(result);
        });
    }
};

/**
 * 查看返修记录
 * @param req
 * @param res
 */
exports.getPaMrs = function(req,res){
    var paid = req.param('paid');
    Pa.findOne({_id:paid},{'pamrs':1},function(err,doc){
        if(err){
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.render('pamrlist',{paid:doc._id,pamrs : doc.pamrs});
        }
    });
};

/**
 * 添加组件的维修记录UI
 */
exports.addPamrUi = function(req,res){
    var paid = req.param('paid');
    res.render('add_pamr',{paid : paid});
};

/**
 * 添加组件的维修记录
 * @param req
 * @param res
 */
exports.addPaMr = function(req,res){
    var paId = req.body.paid;
    var pamrDate = req.body.pamrdate;
    var pamrCon = req.body.pamrcon;
    Pa.findById(paId,function(err,doc){
        doc.pamrs.push({pmt:pamrDate,pmc:pamrCon});
        doc.save(function(err){
            if (err) {
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"dlg_pamrs","forwardUrl":"getPaMrsPost?paid='+paId+'"}');
            };
        });
    });
};

/**
 * 单条删除组件维修记录
 * @param req
 * @param res
 */
exports.deletePaMrOne = function(req,res){
    var paId = req.param('paid');
    var paMrId = req.param('pamrid');
    Pa.findById(paId,{'pamrs':1},function(err,doc){
        doc.pamrs.pull({_id:paMrId});
        doc.save(function(err){
            if (err) {
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"dlg_pamrs","forwardUrl":"getPaMrsPost?paid='+paId+'"}');
            };
        });
    });
};